package com.xingzhe.pengji.security.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xingzhe.pengji.framework.controller.BaseController;

@Controller
public class ImageController extends BaseController
{
    @RequestMapping(value = "/image/{imageName}.jpg", method = RequestMethod.GET)
    public void getImage(@PathVariable String imageName,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("image/jpeg");
        
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;
        
        StringBuilder fname = new StringBuilder();
        fname.append("\\WEB-INF\\images\\");
        fname.append(imageName);
        fname.append(".jpg");
        
        InputStream in=request.getServletContext().getResourceAsStream(fname.toString());
        
        if(in==null)
        {
            in=request.getServletContext().getResourceAsStream("\\WEB-INF\\images\\error\\404.jpg");
        }
        bis = new BufferedInputStream(in);  
        
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[1024];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }
        bos.close();
        bis.close();
    }
}
